import { reactive, toRefs, ref } from "vue";
import md5 from "js-md5";
import { Toast } from "vant";

import { register, login } from "../../../apis/user";
import { setToken } from "../../../utils/auth";

import { useRouter } from "vue-router";

import { useStore } from "vuex";

interface loginType {
    loginName: string;
    password: string;
    verify: string;
    type: Number;
    passwordMd5?: string;
}

export default function loginHook() {
    const verifyRef: any = ref(null);

    const route = useRouter();
    const store = useStore();

    const loginForm = reactive<loginType>({
        loginName: "18280359000",
        password: "q1111111",
        verify: "",
        passwordMd5: "",
        type: 1, // 1登录 2注册
    });

    /* 提交 */
    const onSubmit = async function () {
        console.log(verifyRef.value.imgCode);

        if (
            loginForm.verify.toLowerCase() !=
            verifyRef.value.imgCode.toLowerCase()
        ) {
            Toast.fail("验证码有误");
            loginForm.verify = "";
            drawFun();
            return;
        }
        loginForm.type === 1 ? loginBtn() : registerBtn();
    };

    /* 注册 */
    const registerBtn = async function () {
        loginForm.passwordMd5 = "";
        await register(loginForm);
        Toast.success("注册成功");
        rest();
    };

    /* 登录 */
    const loginBtn = async function () {
        loginForm.passwordMd5 = md5(loginForm.password);
        try {
            let res: any = await login(loginForm);
            Toast.success("登录成功");
            route.replace("/");
            setToken(res.data);
            store.commit("user/setToken", res.data);
        } catch {
            drawFun();
        }
    };

    /* 重置 */
    const rest = function () {
        loginForm.type = loginForm.type === 1 ? 2 : 1;
        loginForm.loginName = "";
        loginForm.password = "";
        loginForm.passwordMd5 = "";
        loginForm.verify = "";
        drawFun();
    };
    const change = () => {
        loginForm.type = loginForm.type === 1 ? 2 : 1;
    };
    const drawFun = function () {
        verifyRef.value.handleDraw();
    };
    return {
        ...toRefs(loginForm),
        verifyRef,
        onSubmit,
        rest,
        change,
    };
}
